package hcb.dms;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import hcb.dms.nhanVien.ChangePassword;


public class login extends Activity {

    private Button btChangePassword, btAbout, btLogin;
    private EditText txUsername, txPassword;
    public UserSessionManager session;
    public static GPSTracker gps;

    JSONParser jsonParser = new JSONParser();
    String username, password, maData;
    // url to create new product

    // JSON Node names

    JSONArray tmpar = null;


    private static final String TAG_SUCCESS = "success";
    private static final String TAG_SESSION = "session";
    private static final String TAG_USERNAME = "username";
    private static final String TAG_PASSWORD = "password";
    private static final String TAG_DATAS = "maData";
    private static final String TAG_MESSAGE = "message";
    JSONArray products = null;
    ArrayList<HashMap<String, String>> productsList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        btChangePassword = (Button) findViewById(R.id.btChangePassword);
        btAbout = (Button) findViewById(R.id.btAbout);

        btLogin = (Button) findViewById(R.id.btLogin);
        txUsername = (EditText) findViewById(R.id.txUserame);
        txPassword = (EditText) findViewById(R.id.txPassword);

        session = new UserSessionManager(getApplicationContext());

        if(session.isUserLoggedIn())
        {
            // neu da login roi thi  goi ham main  luon ket thuc thuc login
            Intent i = new Intent(getApplicationContext(), MainActivity.class);
            startActivity(i);
            // ket thuc loin
            finish();
        }
        // kiem tra trang thai da log in
        Toast.makeText(getApplicationContext(), "User Login Status: " + session.isUserLoggedIn(), Toast.LENGTH_LONG).show();

        gps = new GPSTracker(login.this);
        if (gps.canGetLocation()) {

            double latitude = gps.getLatitude();
            double longitude = gps.getLongitude();

            // \n is for new line
            Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
        } else {
            // can't get location
            // GPS or Network is not enabled
            // Ask user to enable GPS/network in settings
            gps.showSettingsAlert();
        }

        btChangePassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Launching All products Activity
                Intent i = new Intent(getApplicationContext(), ChangePassword.class);
                startActivity(i);

            }
        });
        btAbout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getApplicationContext(), About.class);
                startActivity(i);
            }
        });


        btLogin.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // Validate if username, password is filled
                String username = txUsername.getText().toString();
                String password = txPassword.getText().toString();
                if (username.trim().length() > 0 && password.trim().length() > 0) {
                    new CreateNewLogin().execute();
                } else {
                    // user didn't entered username or password
                    Toast.makeText(getApplicationContext(), "Please enter username and password", Toast.LENGTH_LONG).show();
                }
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.login, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    // tao luong de log in
    class CreateNewLogin extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }
        /**
         * Creating new sesion
         */
        protected String doInBackground(String... args) {
            String username = txUsername.getText().toString();
            String password = txPassword.getText().toString();
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("username", username));
            params.add(new BasicNameValuePair("password", password));
            params.add(new BasicNameValuePair("dangNhap","OK"));
            params.add(new BasicNameValuePair("thaoTac","LOGIN"));
            JSONObject json = jsonParser.makeHttpRequest(session.URL, "POST", params);

            try {
                int success = json.getInt(TAG_SUCCESS);
                if (success == 1) {

                    JSONArray productObj = json.getJSONArray(TAG_SESSION); // JSON Array
                    JSONObject tmp = productObj.getJSONObject(0);

                    session.createUserLoginSession(tmp.getString(TAG_USERNAME),password, tmp.getString(TAG_DATAS));
                  // goi from main
                    Intent i = new Intent(getApplicationContext(), MainActivity.class);
                    startActivity(i);
                  // ket thuc login
                    finish();
                } else {
                    Toast.makeText(getApplicationContext(),json.getInt(TAG_SUCCESS), Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
          ///      Toast.makeText(getApplicationContext(),"Loi ham login.", Toast.LENGTH_LONG).show();
                Log.d(null, "Server out:" + json.toString());
            }
            return null;
        }

    }
}




